<?php
/**
 * 企业微信授权相关类
 * Created by PhpStorm.
 * User: zd
 * Date: 2018/10/8
 * Time: 10:31
 */

namespace app\api\controller\v1;

use app\api\controller\BaseController;
use app\api\service\WorkContact;
use app\api\service\WorkNotify;
use app\api\service\Token;
use app\api\model\Work as WorkModel;
use app\api\validate\WorkNotifyParameter;
use app\api\validate\WorkParameter;
use app\api\validate\WorkPermanentCodeParameter;
use app\lib\exception\SuccessMessage;
use app\lib\exception\TokenException;
use app\lib\exception\WorkException;
use app\lib\exception\WorkInfoException;
use app\lib\exception\WorkPreAuthCodeException;



class Work extends BaseController
{
    protected $beforeActionList=[
        'checkPrimaryScope' => ['only'=>'getPermanentCode,getContactAuthUrl'],
    ];
    /**
     * 企业微信通用开发开发验证url有效性接口
     * 返回企业微信通信标识,验证url的有效性
     * @return string
     */
  public function receiveNotify(){
      (new WorkNotifyParameter())->goCheck();
      $notify = new WorkNotify();
      $sEchoStr =  $notify->get();
    return $sEchoStr;
  }

    /**
     * 用于返回通讯录应用的通信标识，验证url的有效性接收get请求
     * 以及接收微信返回的post请求。获取数据
     * 此应用没有权限限制，对外的公共方法。用于接收微信推送的suite_ticket通知
     * @return string
     * @throws WorkException
     */
  public function getSuite(){
      $notify = new WorkContact();
       if (request()->isGet()){
           (new WorkNotifyParameter())->goCheck();
           $sEchoStr =  $notify->get();
           return $sEchoStr;
       }else if (request()->isPost()){
          (new WorkParameter())->goCheck();
           $sEchoStr =  $notify->getNotify();
           $sEchoStr = 1;
           if ($sEchoStr){
               return 'success';
            }
       }
  }
    /**
     * 返回通讯录预授权码
     * @return \ServiceCorpAPI
     * @throws WorkPreAuthCodeException
     */
  public function getContactPreAuthCode(){
      $contact = new WorkContact();
      $preAuthCode = $contact->getPreAuthCode();
      if (empty($preAuthCode)){
        throw new WorkPreAuthCodeException();
      }
      return  json($preAuthCode);
  }
    /**
     * 传递临时授权码，获取永久授权信息，并存入数据库
     * @param int $code
     * @return \think\response\Json
     * @throws WorkException
     * @throws WorkInfoException
     */
  public function getPermanentCode($code=0){
      (new WorkPermanentCodeParameter())->goCheck();
      $uid = Token::getCurrentUid();
      $contact = new WorkContact();
      $result = $contact->getTestPermanentCode($code);
        if (!$result){
            throw new WorkException([
                'msg'=>'企业微信获取永久授权信息失败'
            ]);
        }
        $info = WorkModel::creatWork($uid,$result);
        if (!$info){
            throw new WorkInfoException();
        }else{
            return json(new SuccessMessage());
        }
  }
    /**
     * 获取通讯录授权url
     * @return string
     */
  public function getContactAuthUrl(){
      $token = Token::getCurrentTokenValue();
      $contact = new WorkContact();
      $url =  $contact->getAuthUrl($token);
    return $url;
  }
    /**
     *接收微信回调
     * @param $auth_code
     * @param $state
     * @return \think\response\Json
     * @throws TokenException
     * @throws WorkException
     * @throws WorkInfoException
     */
    public function receiveUri($auth_code,$expires_in,$state){
        //error_log(print_r($auth_code, 1), 3, "./yzh.txt");
        if (Token::verifyToken($state)) {
            $userInfo = Token::getCurrentToken($state);
            $uid = $userInfo['uid'];
            $contact = new WorkContact();
            $result = $contact->getPermanentCode($auth_code);
          //  error_log(print_r($result, 1), 3, "./yzh.txt");
            if (!$result) {
                throw new WorkException([
                    'msg' => '企业微信获取永久授权信息失败'
                ]);
            }
            $type['type'] = 'contact';
            $info = (new WorkContact)->authorizeContact($uid, $result,$type);
            if (!$info) {
                throw new WorkInfoException();
            } else {
                return json(new SuccessMessage());
            }
        }else{
            throw new TokenException([
                'msg'=>'token检测不通过,请重新授权',
            ]);
        }
    }

    /**
     * 设置通讯录授权配置
     */
    public function setContactAppConfig(){
        $contact = new WorkContact();
        $info =  $contact->setAppConfig();
        return $info;
    }


}